<template>
  <a-layout class="" style="min-height: 100%">
    <a-layout-sider
      class="pl-2 pr-2 layout-sider"
      width="260"
      style="
        background: #fff;
        user-select: none;
        height: calc(100vh - 54px);
        overflow-y: auto;
        position: fixed;
        left: 0;
      "
    >
      <div class="pa-2 pt-3 mb-2 text-right border-bottom">
        <a-tooltip>
          <template #title>新建文件 Ctrl + Alt + N</template>
          <a-button size="small" type="text" @click="addNewFile('file')">
            <FileOutlined />
          </a-button>
        </a-tooltip>
        <a-tooltip>
          <template #title>添加文件夹</template>
          <a-button size="small" type="text" @click="addNewFile('dir')">
            <FileAddOutlined />
          </a-button>
        </a-tooltip>
        <a-button size="small" type="text" @click="getAll">
          <ReloadOutlined />
        </a-button>
      </div>
      <a-dropdown :trigger="['contextmenu']">
        <a-menu mode="inline" @click="handleClick" @openChange="handleMenuOpen">
          <file-list :list="fileTree" @contextClick="contextClick" />
        </a-menu>
        <template #overlay>
          <Contextmenu :id="contextId" :fileMap="fileMap" @success="getAll" />
        </template>
      </a-dropdown>
    </a-layout-sider>
    <a-layout-content class="pa-2 bg-white" style="margin-left: 272px">
      <FileContent />
    </a-layout-content>
  </a-layout>
</template>

<script lang="ts">
import {
  defineComponent,
  ref,
  computed,
  nextTick,
  onMounted,
  onUnmounted,
  watch
} from 'vue'
import { useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import {
  DownOutlined,
  FileAddOutlined,
  FileOutlined,
  EditOutlined,
  ReloadOutlined
} from '@ant-design/icons-vue'
import { addFile, getFile, updataFile, deleteFile } from '@/services'
import { Filetype, FilesModel } from '@/services/service/files'
import { useStore } from 'vuex'
import { DOC_CTRL_ALT_N } from '@/types/constant'
import { Pubsub } from '@/plugins/pubsub'
import { init } from '@/utils/init'
import FileList from './file-list.vue'
import FileContent from './file-content.vue'
import Contextmenu from './contextmenu.vue'

export default defineComponent({
  name: 'home',
  components: {
    DownOutlined,
    FileAddOutlined,
    FileOutlined,
    EditOutlined,
    ReloadOutlined,
    FileList,
    FileContent,
    Contextmenu
  },
  setup() {
    const router = useRouter()
    const store = useStore()
    const files = computed(() => store.state.db.files)
    const connection = computed(() => store.state.db.connection)
    const fileTree = computed(() => store.state.db.fileTree)
    const fileMap = computed<Array<FilesModel>>(() => store.state.db.fileMap)
    const selectedKeys = ref([])
    const openKeys = ref([])
    const currentFile = computed(() => store.state.db.currentFile)
    const openId = ref(0)
    // 右键选中的文件 id
    const contextId = ref(0)

    /** 添加文件 / 文件夹 */
    const addNewFile = async function (type: String) {
      let name = prompt('请输入文件名')
      if (!name) return

      let pid = openId.value || 0
      let res
      if (type === Filetype.file) {
        res = await addFile({
          name: name!,
          type: Filetype.file,
          pid
        })
      } else if (type === Filetype.dir) {
        res = await addFile({
          name,
          type: Filetype.dir,
          pid
        })
      }

      if (res && res.code) {
        message.success('添加成功  id=' + res.data)
        getAll()
      } else {
        message.error(res?.msg || '')
      }
    }
    const handleCtrlN = function () {
      addNewFile(Filetype.file)
    }

    const find = async function () {
      getFile('aa0')
        .then((res) => {
          console.log('find成功', res)
        })
        .catch((err) => {
          console.log('find失败', err)
        })
    }

    const getAll = async function () {
      store.dispatch('db/getFiles')
    }

    /** item 点击 */
    const handleClick = function ({ key }: any) {
      let file = fileMap.value[key]
      // if ((<any>file).id === currentFile.value.id) return

      store.dispatch('db/setCurrentFile', file)
      openId.value = currentFile.value.pid || 0
    }

    /** 菜单打开 */
    const handleMenuOpen = function (items: []) {
      openKeys.value = items
      openId.value = items.slice(-1)[0]
    }

    const contextClick = function (id: number) {
      contextId.value = id
    }

    watch(
      () => connection.value,
      () => {
        if (connection.value) {
          // 初始化语法文档
          init().then((res) => {
            res && getAll()
          })
        }
      },
      { immediate: true }
    )

    onMounted(() => {
      Pubsub.on(DOC_CTRL_ALT_N, handleCtrlN)
    })

    onUnmounted(() => {
      Pubsub.unsubscribe(DOC_CTRL_ALT_N, handleCtrlN)
    })

    return {
      files,
      fileTree,
      fileMap,
      selectedKeys,
      currentFile,
      addNewFile,
      find,
      getAll,
      handleClick,
      handleMenuOpen,
      contextClick,
      contextId
    }
  }
})
</script>

<style lang="less" scoped>
.layout-sider {
  .ant-menu :deep(.anticon) {
    font-size: 17px !important;
  }
}
</style>
